//
//  NewViewController.swift
//  qiubai
//
//  Created by Qingke on 16/5/26.
//  Copyright © 2016年 Qingke. All rights reserved.
//

import UIKit

class NewViewController: UIViewController {
    

    let identifier_cell = "myTbcell"
    var tabelView1: UITableView!
    var count = []
    let page = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUp_views()
        layOut_views()
        
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setUp_views() -> Void {
        self.view.backgroundColor = UIColor.yellowColor()
        //view删除了哪里来的view
        tabelView1 = UITableView()
        let cellNib = UINib(nibName: "myTableViewCell", bundle: nil)
        tabelView1.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
        tabelView1.delegate = self
        tabelView1.dataSource = self
        tabelView1.separatorStyle = .None
        
        tabelView1.registerNib(cellNib, forCellReuseIdentifier: identifier_cell )
        
        //刷新UI的添加
        self.view.addSubview(tabelView1)
    }
    
    //这里用来加载数据
    //当程序开始运行时候就加载一下,将数据传给
    func layOut_views() {
        
        let url = "http://m2.qiushibaike.com/article/list/suggest?count=20&page=\(page)"
        //这里请求是异步的，所以必须在请求完成后再加载数据。
        HttpRequest.requestWithUrl(url) { (data) in
            self.count = data["items"]   as! NSArray //分析joson 发现是数组
            self.tabelView1.reloadData()
            
            //解析 发现了需要的数据，有点赞，有点down
        }
        
    }
    
   
    

}

extension NewViewController: UITableViewDataSource {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.count.count
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(identifier_cell, forIndexPath: indexPath) as? myTableViewCell
        let data = self.count[indexPath.row] as? NSDictionary
        cell?.data = data
        return cell!
    }
    
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.tabelView1
    }
}
extension NewViewController: UITableViewDelegate {
    
}

